package string;

public class LongestPalindrome {
    //最长的回文字符串
    public static String code(String s) {
        int n = s.length();
        int begin = 0, len = 0;

        for (int i = 0; i < n; i++){
            //扩展奇数长度
            int left = i, right = i;
            while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }

            if (right - left - 1 > len){
                begin = left + 1;
                len = right - left - 1;
            }

            //扩展偶数长度
            left = i;
            right = i + 1;
            while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }

            if (right - left - 1 > len){
                begin = left + 1;
                len = right - left - 1;
            }
        }

        return s.substring(begin, begin + len);
    }

    public static void main(String[] args) {
        LongestPalindrome.code("babad");
    }
}
